#include "SSB_system.h"
#include "SSB_sys_def.h"
#include "SSB_wifi.h"
#include "SSB_flash_storage.h"
#include "SSB_uart1.h"
#include "opcol_util.h"
#include "SSB_uart_data_buffer.h"
#include "tcpip_adapter.h"
#include "nvs_flash.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "esp_log.h"
#include "esp_wifi.h"
#include "driver/uart.h"

char UART1_DATA_HEAD_MARK[8] = {0};
char UART1_DATA_END_MARK[8] = {0};
int UART1_DATA_CRC_TYPE = 0;
int UART1_DATA_CRC_LEN = 1;

void SSB_init_system_configuration()
{
    //strcpy(UART1_DATA_HEAD_MARK, "41542B"); //AT+
    strcpy(UART1_DATA_END_MARK, "0A"); //\n
    //80-7D-3A-27-D0-70
    extern char device_id[32];
    extern int data_version;
    extern char ssb_airkiss_wechat_id[32];
    memset(&device_id[0], 0, sizeof(device_id));
    //SSB_read_data_from_nvs_flash(CHIP_ID_FIELD, &device_id[0], sizeof(device_id));
    //if (strlen(device_id) < 1)
    //{
    uint8_t mac[6];
    esp_efuse_mac_get_default(mac);
    //esp_wifi_get_mac(ESP_IF_WIFI_STA, mac);
    sprintf(device_id, "%02X%02X%02X%02X%02X%02X",
            (unsigned int)mac[0],
            (unsigned int)mac[1],
            (unsigned int)mac[2],
            (unsigned int)mac[3],
            (unsigned int)mac[4],
            (unsigned int)mac[5]);

    //SSB_flash_nvs_storage(CHIP_ID_FIELD, (char *)&device_id[0], strlen(device_id));
    ESP_LOGI(SSB_TAG, "Init chip id:%s", device_id);
    //}
    //SSB_LIC_FIELD
    SSB_read_data_from_nvs_flash(DATA_VERSION_FIELD, (char *)&data_version, 4);
    SSB_read_data_from_nvs_flash(SSB_AIRKISS_WECHAT_ID_FIELD, (char *)&ssb_airkiss_wechat_id, sizeof(ssb_airkiss_wechat_id));
}

void SSB_reset_system()
{
    extern int data_version;
    SSB_reset_wifi_configuration();
    data_version = data_version + 1;
    SSB_flash_nvs_storage(DATA_VERSION_FIELD, (char *)&data_version, sizeof(int));
}

void SSB_init_system()
{
    extern char device_id[32];
    extern int data_version;
    nvs_flash_init();
    tcpip_adapter_init();
    SSB_init_system_configuration();
    ESP_LOGI(SSB_TAG, "CHIP ID:%s,Data version:%d", device_id, data_version);
}

void SSB_init_log_uart()
{
    uart_config_t uart_config = {
        .baud_rate = 115200,
        .data_bits = UART_DATA_8_BITS,
        .parity = UART_PARITY_DISABLE,
        .stop_bits = UART_STOP_BITS_1,
        .flow_ctrl = UART_HW_FLOWCTRL_DISABLE};
    uart_param_config(UART_NUM_1, &uart_config);
    uart_driver_install(UART_NUM_1, UART_BUF_SIZE, 0, 0, NULL);
}